import { IndexHtmlTransformContext } from "vite";
import { OutputAsset } from "rollup";

export default function lazyImagePlugin() {
  return {
    name: "vite-plugin-inlinecss",
    enforce: "post",
    apply: "build",
    transformIndexHtml(html, ctx: IndexHtmlTransformContext) {
      // 将html内的入口css改为内联css
      let cssLinks = html.match(
        /<link rel="stylesheet"[^>]*?href="([\./][^>]*)"[^>]*?>/g
      );
      (cssLinks || []).forEach((link) => {
        Object.values(ctx.bundle).forEach((bundle: OutputAsset) => {
          if (link.includes(bundle.fileName)) {
            const reCSS = new RegExp(
              `<link rel="stylesheet"[^>]*?href="[\./]*${bundle.fileName}"[^>]*?>`
            );
            const code = `<style type="text/css">\n${bundle.source}\n</style>`;
            html = html.replace(reCSS, (_) => code);
          }
        });
      });
      return html;
    },
  };
}
